package com.wlit.httpserver;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wlit.print.LabelPrinter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import javax.swing.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 处理http请求
 **/
public class HttpApis extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest request) throws Exception {
        FullHttpResponse response = null;
        if(request.method() == HttpMethod.GET){
            String data = "{\"code\":200,\"msg\":\"success\",\"data\":\""+"\"}";
            ByteBuf buf = copiedBuffer(data, CharsetUtil.UTF_8);
            response = responseOk(HttpResponseStatus.OK,buf);
        }else if(request.method() == HttpMethod.POST){
            if (!LabelPrinter.getInstance().isOpen()){
                showMessage("打印机未连接，请先连接打印机");
                return;
            }

            ByteBuf content = request.content();
            byte[] reqContent = new byte[content.readableBytes()];
            content.readBytes(reqContent);
            String strContent = new String(reqContent, StandardCharsets.UTF_8);

            JSONArray jsonArray = null;
            try {
                jsonArray = JSONObject.parseArray(strContent);
            }catch (Exception e){
                e.printStackTrace();
            }
            if (jsonArray == null){
                showMessage("打印数据格式错误");
                return;
            }

            if(jsonArray != null && jsonArray.size() > 0){
                for(int i = 0; i < jsonArray.size(); i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    LabelPrinter.getInstance().print(jsonObject);
                }
            }

            ByteBuf buf = copiedBuffer(strContent, CharsetUtil.UTF_8);
            response = responseOk(HttpResponseStatus.OK,buf);
        }else{
            response = responseOk(HttpResponseStatus.INTERNAL_SERVER_ERROR,null);
        }
        // 发送响应
        channelHandlerContext.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private ByteBuf copiedBuffer(String data, Charset utf8) {
        return Unpooled.wrappedBuffer(data.getBytes());
    }

    private void showMessage(String message){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(null, message);
            }
        });
    }

    private FullHttpResponse responseOk(HttpResponseStatus status, ByteBuf buf) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                status,buf);
        if(buf != null){
            response.headers().set("Content-Type","text/plain;charset=UTF-8");
            response.headers().set("Content-Length",response.content().readableBytes());
        }
        return response;
    }





}
